package com.hu.gulimallproduct.config.exception;

import com.hu.gulimallcommon.exception.ValidEnum;
import com.hu.gulimallcommon.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice(basePackages = "com.hu.gulimallproduct.project.controller")
public class GulimallExceptionAdvice {
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handValidException(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        Map<String,String> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach(fieldError -> errorMap.put(fieldError.getField(),fieldError.getDefaultMessage()));
        log.error( e.getMessage(),e.getClass());
        return R.error(ValidEnum.VALID_ERROR.getCode(),"参数错误").put(ValidEnum.VALID_ERROR.getMsg(), errorMap);

    }
}
